﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;

namespace JustMetClient.Tools
{
    public class ComputerMonitor
    {
        #region 属性
        //CPU信息
        public string CpuInfo = "";
        //显卡信息    
        public string GraphicsCardInfo = "";
        //声卡信息
        public string AudioDeviceInfo = "";
        //物理内存
        public string PhysicalMemory = "";

        //CPU ID
        public string CpuID = "";
        //硬盘信息
        public string HDiskInfo = "";
        //硬盘ID
        public string HDiskID = "";
        //MAC 地址
        public string MacAddress = "";
        //网卡信息
        public string NetworkCardInfo = "";
        //IP 地址
        public string IpAddress = "";
        //操作系统
        public string OS = "";
        //系统类型
        public string SystemType = "";
        //系统安装时间
        public string SystemInstallDate = "";
        //登陆用户名
        public string LoginUserName = "";
        //计算机名
        public string ComputerName = "";
        //计算机所有用户
        public List<string> SysUserNames = null;

        //主板制造商
        public string BoardManufacturer { get; set; }
        //主板型号
        public string BoardProduct { get; set; }
        //主板ID
        public string BoardSerialNumber { get; set; }
        #endregion

        #region 构造方法
        public ComputerMonitor()
        {
            Init();
        }
        #endregion

        #region 加载所有配置信息
        public void Init()
        {
            //获取CPU ID
            CpuID = GetCpuID();
            //获取硬盘ID
            HDiskID = GetHDiskID(HDiskInfo);
            //获取系统类型
            SystemType = GetSystemType();
            //获取计算机名
            ComputerName = GetComputerName();
            //获取所有用户名
            SysUserNames = GetSysUserNames();
            //获取主板ID
            BoardSerialNumber = GetBoardSerialNumber();
            //获取主板制造商
            BoardManufacturer = GetBoardManufacturer();
            //获取主板型号
            BoardProduct = GetBoardProduct();
        }
        #endregion

        #region 获取信息方法
        #region 获取CPU ID
        public string GetCpuID()
        {
            try
            {
                string result = "";
                ManagementClass mc = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    result = mo.Properties["ProcessorId"].Value.ToString();
                }
                return result;
            }
            catch
            { return "unknown"; }
        }
        #endregion 
        #region 获取硬盘ID
        public string GetHDiskID(string hdModel)
        {
            try
            {
                string result = "";
                ManagementClass mc = new ManagementClass("Win32_DiskDrive");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if (mo.Properties["Model"].Value.ToString().Contains(hdModel))
                    {
                        result = (string)mo.Properties["SerialNumber"].Value;
                    }
                }
                return result.Trim();
            }
            catch
            { return "unknown"; }
        }
        #endregion
        #region 获取系统类型
        public string GetSystemType()
        {
            try
            {
                string result = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {

                    result = mo["SystemType"].ToString();

                }
                return result;
            }
            catch
            { return "unknown"; }
        }
        #endregion
        #region 获取计算机名
        public string GetComputerName()
        {
            try
            {
                string result = "";
                result = System.Environment.GetEnvironmentVariable("ComputerName");
                return result;
            }
            catch
            { return "unknown"; }
        }
        #endregion
        #region 获取所有用户名
        public List<string> GetSysUserNames()
        {
            int EntriesRead;
            int TotalEntries;
            int Resume;
            IntPtr bufPtr;
            List<string> temp = new List<string>();

            NetUserEnum(null, 0, 2, out bufPtr, -1, out EntriesRead, out TotalEntries, out Resume);
            if (EntriesRead > 0)
            {
                USER_INFO_0[] Users = new USER_INFO_0[EntriesRead];
                IntPtr iter = bufPtr;
                for (int i = 0; i < EntriesRead; i++)
                {
                    Users[i] = (USER_INFO_0)Marshal.PtrToStructure(iter, typeof(USER_INFO_0));
                    iter = (IntPtr)((long)iter + Marshal.SizeOf(typeof(USER_INFO_0)));
                    temp.Add(Users[i].Username);
                }
                NetApiBufferFree(bufPtr);
            }
            return temp;
        }
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct USER_INFO_0
        {
            public string Username;
        }
        [DllImport("Netapi32.dll ")]
        extern static int NetUserEnum([MarshalAs(UnmanagedType.LPWStr)]
        string servername,
                int level,
                int filter,
                out IntPtr bufptr,
                int prefmaxlen,
                out int entriesread,
                out int totalentries,
                out int resume_handle);

        [DllImport("Netapi32.dll ")]
        extern static int NetApiBufferFree(IntPtr Buffer);
        #endregion
        #region 获取主板制造商
        public string GetBoardManufacturer()
        {
            try
            {
                string result = "";
                ManagementObjectSearcher MySearcher = new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");
                foreach (ManagementObject MyObject in MySearcher.Get())
                {
                    result = MyObject["Manufacturer"].ToString();
                }
                return result;
            }
            catch
            { return "unknown"; }
        }
        #endregion
        #region 获取主板型号
        public string GetBoardProduct()
        {
            try
            {
                string result = "";
                ManagementObjectSearcher MySearcher = new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");
                foreach (ManagementObject MyObject in MySearcher.Get())
                {
                    result = MyObject["Product"].ToString();
                }
                return result;
            }
            catch
            { return "unknown"; }
        }
        #endregion
        #region 获取主板序列号
        public string GetBoardSerialNumber()
        {
            try
            {
                string result = "";
                ManagementObjectSearcher MySearcher = new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");
                foreach (ManagementObject MyObject in MySearcher.Get())
                {
                    result = MyObject["SerialNumber"].ToString();
                }
                return result;
            }
            catch
            { return "unknown"; }
        }
        #endregion
        #endregion 
        #region 获取计算机默认共享列表
        public static List<string> GetSystemShare()
        {
            List<string> rs = new List<string>();
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from win32_share");
            foreach (ManagementObject share in searcher.Get())
            {
                try
                {
                    string name = share["Name"].ToString();
                    string path = share["Path"].ToString();
                    rs.Add(name + ">>" + path);
                }
                catch (Exception ex) { }
            }
            return rs;
        } 
        #endregion 
         
        #region 获取USB使用记录
        public static List<string> GetUSBRecord()
        {
            List<string> rs = new List<string>();
            //定义注册表顶级节点 其命名空间是using Microsoft.Win32;  
            RegistryKey USBKey;
            //检索子项      
            USBKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Enum\USBSTOR", false);
            //检索所有子项USBSTOR下的字符串数组  
            foreach (string sub1 in USBKey.GetSubKeyNames())
            {
                RegistryKey sub1key = USBKey.OpenSubKey(sub1, false);
                foreach (string sub2 in sub1key.GetSubKeyNames())
                {
                    try
                    {
                        //打开sub1key的子项  
                        RegistryKey sub2key = sub1key.OpenSubKey(sub2, false);
                        //检索Service=disk(磁盘)值的子项 cdrom(光盘)  
                        if (sub2key.GetValue("Service", "").Equals("disk"))
                        {
                            String Path = "USBSTOR" + "\\" + sub1 + "\\" + sub2;
                            String Name = (string)sub2key.GetValue("FriendlyName", "");

                            string info = "Name=" + Name + "&&UID=" + sub2 + "&&Path=" + Path;
                            //处理反斜杠
                            info = info.Replace("\\", "\\\\");
                            rs.Add(info + "&");
                        }
                    }
                    catch { }
                }
            }
            return rs;
        }
        #endregion 

        #region 同步时间
        public static bool SyncTime()
        {
            bool succ = false;
            try
            {
                //参数
                string WebIp = ConfigurationManager.AppSettings["ServerIP"];
                int webPort = int.Parse(ConfigurationManager.AppSettings["WebPort"]);
                string url = string.Format("http://{0}:{1}/noah/webservice/getServerTime", WebIp, webPort);
                string pageHtml = "";
                DateTime dateTime;
                //请求时间

                WebClient MyWebClient = new WebClient();
                MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
                Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据
                pageHtml = Encoding.Default.GetString(pageData); //如果获取网站页面采用的是GB2312，则使用这句 

                //pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8，则使用这句

                //转换时间并更新
                if (!string.IsNullOrEmpty(pageHtml))
                {
                    dateTime = DateTime.Parse(pageHtml);
                    if (dateTime.Year >= 2016)
                    {
                        //string d = RunCommand("date " + dateTime.ToString("yyyy-MM-dd"));
                        //string t = RunCommand("time " + dateTime.ToString("HH:mm:ss"));
                        SystemDateTime.SetLocalTimeByStr(dateTime.ToString());
                        succ = true;
                    }
                }
            }
            catch (Exception e) { }
            return succ;
        }
        #endregion
    }
}